﻿using System.Net;
using OnHook.Business.IServices.Common;
using OnHook.Common.Extension;
using OnHook.Framework.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.Features;

namespace OnHook.WebApi.Middleware
{
    /// <summary>
    /// Token校验中间件
    /// </summary>
    public class JwtValidateMiddleware(RequestDelegate next)
    {
        private readonly RequestDelegate _next = next;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext httpContext)
        {
            //排除swagger
            if (httpContext.Request.Path.Value?.StartsWith("/swagger") ?? false)
            {
                await _next(httpContext);
                return;
            }
            var allowAnonymouse = httpContext.Features.GetRequiredFeature<IEndpointFeature>()?.Endpoint?.Metadata.GetMetadata<AllowAnonymousAttribute>();
            if (allowAnonymouse != null)
            {
                await _next(httpContext);
                return;
            }

            var jwtSerivce = httpContext.RequestServices.GetService<IJwtService>();
            var token = httpContext.Request.Headers.Authorization.FirstOrDefault()?.ToString() ?? "";
            if (token.IsNotEmpty() && jwtSerivce != null)
            {
                var userInfo = jwtSerivce.GetLoginUserVoByToken(token, out _);
                if (userInfo != null)
                {
                    await _next(httpContext);
                    return;
                }
            }
            httpContext.Response.ContentType = "application/json";
            httpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            await httpContext.Response.WriteAsJsonAsync(ApiResult.Failed((int)HttpStatusCode.Unauthorized, "未授权访问"));
        }
    }
}
